package com.easyxu.kubernetes.filebrowser.service.executor;

import com.easyxu.kubernetes.filebrowser.service.dto.DirectoryQryCmd;
import com.easyxu.kubernetes.filebrowser.service.dto.data.DirectoryDto;
import com.google.common.io.CharStreams;
import io.kubernetes.client.Exec;
import io.kubernetes.client.openapi.ApiException;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class DirectoryQryCmdExe {

    public List<DirectoryDto> execute(DirectoryQryCmd cmd) throws IOException, ApiException {
        Exec exec = new Exec();
        final Process process = exec.exec(cmd.getNamespace(), cmd.getPod(),
                new String[]{"sh", "-c", "ls -F " + cmd.getPath()}, false);

        List<String> directorys = CharStreams.readLines(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));

        process.destroy();
        List<DirectoryDto> directoryDtos = directorys.stream()
                .map(directory-> directoryToDto(cmd.getPath(), directory))
                .collect(Collectors.toList());

        return directoryDtos.stream().sorted(((o1, o2) -> sortedOrder(o1,o2)))
                .collect(Collectors.toList());
    }

    private int sortedOrder(DirectoryDto dto1, DirectoryDto dto2){
        if(dto1.isDirectory()){
            return -1;
        }
        if(dto2.isDirectory()){
            return 1;
        }
        return 0;
    }

    private DirectoryDto directoryToDto(String path, String directory){
        boolean isDirectory = directory.endsWith("/");
        String directoryFullPath;
        if(path.equals("/")){
            directoryFullPath = path + directory;
        }else{
            directoryFullPath = path + "/" + directory;
        }
        return DirectoryDto.builder()
                .directory(isDirectory)
                .path(directoryFullPath)
                .name(directory)
                .build();
    }
}
